//
//  SQLCenter.m
//  ASVN
//
//  Created by Cuongth on 9/30/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "DBCenter.h"
//#import "Store.h"
//#import "Category.h"

@implementation DBCenter

- (DBCenter*) init{
	if (self = [super init]) {
		[DBCenter copyDatabaseIfNeeded];
		sqlite3_open([[DBCenter getDBPath] UTF8String], &database); 
	}
	
	return self;
}

- (NSString*) getToken:(NSInteger)tokenType{
	NSString *token = nil;
//	const char *sql = (tokenType == 0) ? "SELECT value	FROM config WHERE code = 0" : "SELECT value	FROM config WHERE code = 1";
	NSString *temp = [NSString stringWithFormat:@"SELECT value	FROM config WHERE code = %d", tokenType];
	const char *sql = [temp UTF8String];
	
	sqlite3_stmt *selectstmt;
	
	if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
		while(sqlite3_step(selectstmt) == SQLITE_ROW) {			
			token = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];	
			sqlite3_finalize(selectstmt);
			break;
		}
	}
	
	NSLog(@"ResultToken: %@", token);
		
	return token;
}

- (void) setToken:(NSString*)token WithTokenType:(NSInteger)tokenType{
	NSLog(@"Token to set: %@", token);
	
	char *update = "INSERT OR REPLACE INTO config (code, value) VALUES (?, ?);";
	sqlite3_stmt *stmt;

	if (sqlite3_prepare_v2(database, update, -1, &stmt, nil) == SQLITE_OK) {
		sqlite3_bind_int(stmt, 1, tokenType);
		sqlite3_bind_text(stmt, 2, [token UTF8String], -1, NULL);
	}
	
	if (sqlite3_step(stmt) != SQLITE_DONE)
//		NSAssert1(0, @"Error updating table: %s", errorMsg);
		return;
	
	sqlite3_finalize(stmt);
}

// saving and loading store for cache
//- (NSArray*) getStores{
//	const char *select = "SELECT * FROM Store";	
//	sqlite3_stmt *selectstmt;
//	NSMutableArray *stores = [[NSMutableArray alloc] init];
//	
//	if(sqlite3_prepare_v2(database, select, -1, &selectstmt, NULL) == SQLITE_OK) {		
//		while(sqlite3_step(selectstmt) == SQLITE_ROW) {			
//			Store *s = [[Store alloc] init];
//			
//			s.storeID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];	
//			s.storeName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];	
//			s.storeIconUrl = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];	
//			s.storeIsActive= sqlite3_column_int(selectstmt, 3);				
//			
//			NSLog(@"Store From DB: %@", s.storeID);
//			
//			[stores addObject:s];
//		}
//	}
//		
//	sqlite3_finalize(selectstmt);	
//	return [stores count] > 0 ? stores : nil;	
//}
//
//- (void) saveStore:(Store*)s{
//	NSLog(@"SaveStore: %@", [s storeID]);
//	char *update = "INSERT OR REPLACE INTO Store (id, name, imageurl, isactive) VALUES (?, ?, ?, ?);";
//	sqlite3_stmt *stmt;
//	
//	if (sqlite3_prepare_v2(database, update, -1, &stmt, nil) == SQLITE_OK) {
//		sqlite3_bind_text(stmt, 1, [[NSString stringWithFormat:@"%@", s.storeID] UTF8String], -1, NULL);
//		sqlite3_bind_text(stmt, 2, [(s.storeName) ? s.storeName : @"" UTF8String], -1, NULL);
//		sqlite3_bind_text(stmt, 3, [(s.storeIconUrl) ? s.storeIconUrl : @"" UTF8String], -1, NULL);
//		sqlite3_bind_int(stmt, 4, s.storeIsActive);		
//	}
//	
//	if (sqlite3_step(stmt) != SQLITE_DONE)
//		return;
//	
//	sqlite3_finalize(stmt);	
//}
//
//- (void) clearAllStores{
//
//}
//
//// Saveing and loading category for cache
//- (NSArray*) getCategoriesWithStore:(NSString*)storeId{
//	NSString *sql = [NSString stringWithFormat:@"SELECT * FROM Category where storeid = '%@'", storeId];
//	const char *select = [sql UTF8String];
//	sqlite3_stmt *selectstmt;
//	NSMutableArray *categories = [[NSMutableArray alloc] init];
//	
//	if(sqlite3_prepare_v2(database, select, -1, &selectstmt, NULL) == SQLITE_OK) {		
//		while(sqlite3_step(selectstmt) == SQLITE_ROW) {			
//			Category *c = [[Category alloc] init];
//			NSLog(@"Load Category from server");
//			c.categoryId = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];	
//			c.categoryName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];	
//			c.categoryImageURL = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];	
//			c.numberOfNewItems = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];							
//			
//			[categories addObject:c];
//		}
//	}
//	
//	sqlite3_finalize(selectstmt);	
//	return [categories count] > 0 ? categories : nil;	
//}
//
//- (void) saveCategory:(Category*)c withStoreId:(NSString*)storeId{
//	NSLog(@"Cagegory: %@", [c categoryId]);
//	char *update = "INSERT OR REPLACE INTO Category (id, name, imageurl, newItems, storeId) VALUES (?, ?, ?, ?, ?);";
//	sqlite3_stmt *stmt;
//	
//	if (sqlite3_prepare_v2(database, update, -1, &stmt, nil) == SQLITE_OK) {
//		sqlite3_bind_text(stmt, 1, [[NSString stringWithFormat:@"%@", c.categoryId] UTF8String], -1, NULL);
//		sqlite3_bind_text(stmt, 2, [(c.categoryName) ? c.categoryName : @"" UTF8String], -1, NULL);
//		sqlite3_bind_text(stmt, 3, [(c.categoryImageURL) ? c.categoryImageURL : @"" UTF8String], -1, NULL);
//		sqlite3_bind_text(stmt, 4, [[NSString stringWithFormat:@"%@", c.numberOfNewItems] UTF8String], -1, NULL);
//		sqlite3_bind_text(stmt, 5, [[NSString stringWithFormat:@"%@", storeId] UTF8String], -1, NULL);
//	}
//	
//	if (sqlite3_step(stmt) != SQLITE_DONE)
//		return;
//	
//	sqlite3_finalize(stmt);		
//}
//
//- (void) clearAllCategories{
//	
//}

// Some static method
+ (void) copyDatabaseIfNeeded {
	//Using NSFileManager we can perform many file system operations.
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSError *error;
	NSString *dbPath = [DBCenter getDBPath];
	BOOL success = [fileManager fileExistsAtPath:dbPath]; 
	
	if(!success) {		
		NSLog(@"CopyDB");
		
		NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DBName];
		success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
		
		if (!success) 
			NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
	}	
}

+ (NSString *) getDBPath {
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
	NSString *documentsDir = [paths objectAtIndex:0];
	return [documentsDir stringByAppendingPathComponent:DBName];
}

@end



























